package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentImpl implements IStrategyCommentService{

    @Autowired
    private IStrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment comment) {
        //mongodb里面save是保存又是更新操作
        //所以要通过id判断是保存还是更新
        if (!StringUtils.hasLength(comment.getId())){
            //如果是保存操作的话要设置发布评论时间
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //content
        //totalPages
        //totalElements
        //拼接条件 select count(id) from ** where ..
        Query query = new Query();
        if (qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查询总数
        long count = template.count(query, StrategyComment.class);
        if (count == 0){
            return Page.empty();
        }
        //当前页显示
        //第一个参数约定从0开始,第二个每页显示条数,第三个排序规则，第四个按哪个字段排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "createTime");
        query.with(pageable);
        List<StrategyComment> comments = template.find(query, StrategyComment.class);
        //由于dubbo的序列化，外面PageImpl没有空参构造器，所以要用kroy序列化
        //1.配置到服务生产者  2.添加依赖
        return new PageImpl(comments, pageable, count);
    }

    @Override
    public void commentThumbUp(String detailId, Long userId) {
        //通过id获取StrategyComment的信息
        StrategyComment comment = repository.findById(detailId).get();
        //查看当前点赞的人数（集合）
        List<Long> list = comment.getThumbuplist();
        //点赞发出请求后判断点赞人的集合里面有没有当前登陆用户的id
        if (list.contains(userId)){
            //点赞里面有这个用户的id就证明已经点过赞，所以要取消点在并且把点赞数减一和把当前用户的id从集合里面删除
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            list.remove(userId);
        }else {
            //点赞里面没有这个用户的id就证明没 点过赞，所以要顶赞并且把点赞数加一和把当前用户的id添加进集合里面
            comment.setThumbupnum(comment.getThumbupnum() + 1);
             list.add(userId);
        }
        repository.save(comment);
    }
}
